package atom.core2.j2ee.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import atom.core0.exception.BizException;
import atom.core0.util.StringUtil;
import atom.core2.j2ee.util.RequestManager;

/**
 * @类名称：XssSqlInjectionfilter
 * @类描述：拦截各种Web注入过滤器
 * @作者：zhanggy
 * @日期：2016-6-8
 */
public class XssSqlInjectionfilter implements Filter {
	private final static Logger log = Logger.getLogger(XssSqlInjectionfilter.class);

	public void destroy() {
	}

	@SuppressWarnings("rawtypes")
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;

		String url = request.getRequestURI();
		// String method = request.getParameter("method");

		// 获得所有请求参数名
		Enumeration params = request.getParameterNames();
		while (params.hasMoreElements()) {
			String name = params.nextElement().toString();
			if (excludedValidate(name))
				continue;

			String[] value = request.getParameterValues(name);
			for (int i = 0; i < value.length; i++) {
				if (StringUtils.isNotEmpty(value[i])) {
					// 排除拦截
					if (excludedValidate(value[i]))
						continue;
					// 拦截SQL
					if (sqlValidate(value[i])) {
						request.setAttribute("msg_type", "error");
						request.setAttribute("msg_info", "您提交的数据中含有SQL特殊字符");
						if (StringUtil.isEmpty(XssSqlConfig.errorjsp))
							RequestManager.returnTextMsg(response, "您提交的数据中含有SQL特殊字符", "GBK");
						else
							// "/views/common/notice_warning.jsp"
							request.getRequestDispatcher(XssSqlConfig.errorjsp).forward(request, response);
						return;
					}
					// 拦截跨站脚本
					if (htmlValidate(value[i])) {
						request.setAttribute("msg_type", "error");
						request.setAttribute("msg_info", "您提交的数据中含有Html特殊字符");
						if (StringUtil.isEmpty(XssSqlConfig.errorjsp))
							RequestManager.returnTextMsg(response, "您提交的数据中含有Html特殊字符", "GBK");
						else
							// "/views/common/notice_warning.jsp"
							request.getRequestDispatcher(XssSqlConfig.errorjsp).forward(request, response);

						return;
					}
					// 拦截跨站脚本
					if (htmlpatternValidate(value[i])) {
						request.setAttribute("msg_type", "error");
						request.setAttribute("msg_info", "您提交的数据中含有JavaScript特殊字符");

						if (StringUtil.isEmpty(XssSqlConfig.errorjsp))
							RequestManager.returnTextMsg(response, "您提交的数据中含有JavaScript特殊字符", "GBK");
						else
							// "/views/common/notice_warning.jsp"
							request.getRequestDispatcher(XssSqlConfig.errorjsp).forward(request, response);
						return;
					}
				}
			}
		}
		chain.doFilter(arg0, arg1);
	}

	public void init(FilterConfig arg0) throws ServletException {
		try {
			XssSqlConfig.initConfig();
		} catch (BizException e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * @功能描述：排除检测参数
	 * @param str
	 * @return
	 */
	protected static boolean excludedValidate(String str) {
		String[] KEYWORDS = XssSqlConfig.configMap.get(XssSqlConfig.EXCLUDED).split("\\|");
		String lowerCase = str.toLowerCase();
		for (int i = 0; i < KEYWORDS.length; i++) {
			if (lowerCase.contains(KEYWORDS[i])) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @功能描述：防SQL注入攻击
	 * @param str
	 * @return
	 */
	protected static boolean sqlValidate(String str) {
		String[] KEYWORDS = XssSqlConfig.sql_keywords; // XssSqlConfig.configMap.get(XssSqlConfig.SQLKEYWORD).split("\\|");
		String lowerCase = str.toLowerCase();
		for (int i = 0; i < KEYWORDS.length; i++) {
			if (StringUtil.isEmpty(KEYWORDS[i]))
				continue;
			if (lowerCase.contains(KEYWORDS[i])) {
				log.info(lowerCase + "------------" + KEYWORDS[i]);

				return true;
			}
		}
		return false;
	}

	/**
	 * @功能描述：防跨站脚本攻击
	 * @param str
	 * @return
	 */
	protected static boolean htmlValidate(String str) {
		String[] KEYWORDS = XssSqlConfig.html_keywords;// XssSqlConfig.configMap.get(XssSqlConfig.HTMLKEYWORD).split("\\|");
		String lowerCase = str.toLowerCase();
		for (int i = 0; i < KEYWORDS.length; i++) {
			if (StringUtil.isEmpty(KEYWORDS[i]))
				continue;
			if (lowerCase.contains(KEYWORDS[i])) {
				log.info(lowerCase + "------------" + KEYWORDS[i]);

				return true;
			}
		}
		return false;
	}

	/**
	 * @功能描述：URL检测
	 * @param str
	 * @return
	 */
	protected static boolean htmlpatternValidate(String str) {
		String[] KEYWORDS = XssSqlConfig.html_patterns;// XssSqlConfig.configMap.get(XssSqlConfig.HTML_PATTERN).split("\\|");
		String lowerCase = str.toLowerCase().trim();
		for (int i = 0; i < KEYWORDS.length; i++) {
			if (StringUtil.isEmpty(KEYWORDS[i]))
				continue;
			Pattern SCRIPT_PATTERN = Pattern.compile(KEYWORDS[i]);
			Matcher m = SCRIPT_PATTERN.matcher(lowerCase);
			if (m.find()) {
				log.info(lowerCase + "------------" + KEYWORDS[i]);
				return true;
			} else
				continue;

		}
		return false;
	}

}
